package com.apes.project.jekunAuto.timeTask.customerCar;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.crm.car.model.CarBase;
import com.apes.crm.car.model.CarBusiness;
import com.apes.crm.car.model.CarMaintenance;
import com.apes.crm.car.repository.CarBaseRepository;
import com.apes.crm.customerCar.model.CustomerCar;
import com.apes.crm.customerCar.model.CustomerCarsInsurance;
import com.apes.crm.customerCar.repository.CustomerCarInsuranceRepository;
import com.apes.crm.customerCar.repository.CustomerCarRepository;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.project.jekunAuto.timeTask.BaseService;

import com.apes.scm.masterdata.car.model.CarConfiguration;
import com.apes.scm.masterdata.car.repository.CarConfigurationRepository;
import com.apes.scm.masterdata.contrast.model.ContrastPartyCode;
import com.apes.scm.masterdata.contrast.repository.ContrastPartyCodeRepository;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.party.model.Party;
import com.apes.scm.masterdata.party.model.PartyRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("customerCarSynService")
public class CustomerCarSynService extends BaseService {
    @Autowired
    CarBaseRepository carBaseRepository;

    @Autowired
    ContrastPartyCodeRepository contrastPartyCodeRepository;

    @Autowired
    CustomerCarRepository customerCarRepository;

    @Autowired
    CustomerCarInsuranceRepository customerCarInsuranceRepository;

    @Autowired
    CarConfigurationRepository carConfigurationRepository;

   // 同步客户车辆信息 （原yyerp为会员车辆信息）
    public JSONArray synCustomerCar(SimpleRequest simpleRequest) {
        return getData("ipmVipService.getVipCar");
    }

    // 只同步非会员和会员车辆信息， 没有会员编码的车辆信息不同步
    public void saveCustomerCar(SimpleRequest simpleRequest) {

        JSONObject simpleRequestObj = simpleRequest.getJO();
        // 会员编码
        String vipId = simpleRequestObj.getString("VIPID");
        Party party;
        if (vipId == null) {
            return;
        } else {
            // 检查对照表是否已经有数据, 有的话说明已有会员数据
            ContrastPartyCode contrastPartyCode = contrastPartyCodeRepository.findFirstByVipid(vipId);
            if(contrastPartyCode == null) {
                // 判断车辆，会员是否都已建档
                CarBase carBaseOld = carBaseRepository.findFirstByOriginEquals(simpleRequestObj.getString("CLNM"));
                if(carBaseOld != null) {
                    return;
                }
                throw new RuntimeException("会员信息未同步！");
            }else {
                party = contrastPartyCode.getParty();
            }
        }
        // 保存或更新车辆信息
        CarBase carBase = saveCarInfo(simpleRequest);

        // 保存或者更新会员车辆信息
        CustomerCar customerCar = simpleRequest.getO(CustomerCar.class);

        // 查询会员车辆信息是否存在
        CustomerCar customerCarOld = customerCarRepository.findFirstByPartyEqualsAndCarEquals(party,carBase);
        if (customerCarOld != null) {
            customerCar.setId(customerCarOld.getId());
            customerCar.setVersion(customerCarOld.getVersion());
        }
        customerCar.setParty(party);
        customerCar.setCar(carBase);
        // 车牌类型 0：临时牌， 1： 正式牌
        int CPLX = simpleRequestObj.getInteger("CPLX") != null ? simpleRequestObj.getInteger("CPLX") : 1;
        Enumeration plateType = new Enumeration();
        if(CPLX == 0) {
            plateType.setId("000216");
        }else {
            plateType.setId("000217");
        }
        customerCar.setPlateType(plateType);
        // 使用性质 1:营运 2： 非营运
        int SYXZ = simpleRequestObj.getInteger("SYXZ") != null ? simpleRequestObj.getInteger("SYXZ") : 3;
        if(SYXZ != 3) {
            Enumeration natureOfUse = new Enumeration();
            if(SYXZ == 1) {
                natureOfUse.setId("000218");
            }else if(SYXZ == 2){
                natureOfUse.setId("000219");
            }else {
                natureOfUse = null;
            }
            customerCar.setNatureOfUse(natureOfUse);
        }
        // 是否过户 '1':过户;'2':未过户
        String QCSFGH = simpleRequestObj.getString("QCSFGH");
        if("1".equals(QCSFGH)) {
            customerCar.setCarTransfer(true);
        }else {
            customerCar.setCarTransfer(false);
        }
        // 是否抵押 （yyerp 0:是;1:否 ,还可以为空）
        int DYQK = simpleRequestObj.getInteger("DYQK") != null ? simpleRequestObj.getInteger("DYQK") : 1;
        if(DYQK == 1) {
            customerCar.setCarMortgage(false);
        }else {
            customerCar.setCarMortgage(true);
        }

        // 车辆所有权
        int CLSYQ = simpleRequestObj.getInteger("CLSYQ") != null ? simpleRequestObj.getInteger("CLSYQ") : 2;
        if(CLSYQ != 2) {
            Enumeration carOwnership = new Enumeration();
            if(CLSYQ == 1) {
                carOwnership.setId("000221");
            }else if(CLSYQ == 0){
                carOwnership.setId("000220");
            }else {
                carOwnership = null;
            }
            customerCar.setCarOwnership(carOwnership);
        }
        // 车辆状态 （0：正常在用:1：寄售中:2：已报废）
        int CLZT = simpleRequestObj.getInteger("CLZT") != null ? simpleRequestObj.getInteger("CLZT") : 3;
        if(CLZT != 3) {
            Enumeration carStatus = new Enumeration();
            if(CLZT == 0) {
                carStatus.setId("000222");
            }else if(CLZT == 1) {
                carStatus.setId("000223");
            }else {
                carStatus.setId("000224");
            }
            customerCar.setCarStatus(carStatus);
        }
        // 车辆冻结状态 (0:冻结;1:启用
        int CLDJZT = simpleRequestObj.getInteger("CLDJZT") != null ? simpleRequestObj.getInteger("CLDJZT") : 1;
        Enumeration carFrostStatus = new Enumeration();
        if(CLDJZT == 0) {
            carFrostStatus.setId("000225");
        }else {
            carFrostStatus.setId("000226");
            // 更新该车辆绑定的其他会员的客户车辆信息为冻结状态
            // 老系统车辆信息存在更换会员信息的情况
            customerCarRepository.updateCustomerCarFrost(carBase.getId(),party.getId());
        }
        customerCar.setCarFrostStatus(carFrostStatus);

        customerCar = customerCarRepository.saveAndFlush(customerCar);

        // 保存或者更新会员车辆保险信息
        CustomerCarsInsurance customerCarsInsurance = simpleRequest.getO(CustomerCarsInsurance.class);
        // 查询是否已经存在
        CustomerCarsInsurance customerCarsInsuranceOld = customerCarInsuranceRepository.findFirstByPartyEqualsAndCarEquals(party,carBase);

        if(customerCarsInsuranceOld != null) {
            customerCarsInsurance.setId(customerCarsInsuranceOld.getId());
            customerCarsInsurance.setVersion(customerCarsInsuranceOld.getVersion());
        }
        customerCarsInsurance.setParty(party);
        customerCarsInsurance.setCar(carBase);
        // 交强险公司
        String strongCompanyId = simpleRequestObj.getString("JQXBXGSID");
        PartyRole strongCompany = getInsuranceCompany(strongCompanyId);
        customerCarsInsurance.setStrongCompany(strongCompany);
        // 商业险公司
        String commercialCompanyId = simpleRequestObj.getString("SYXBXGSID");
        PartyRole commercialCompany = getInsuranceCompany(commercialCompanyId);
        customerCarsInsurance.setCommercialCompany(commercialCompany);

        customerCarsInsurance = customerCarInsuranceRepository.saveAndFlush(customerCarsInsurance);
    }

    // 保险公司编码转换成PartyRole对象
    private PartyRole getInsuranceCompany(String companyId) {
        if(companyId == null) return null;
        PartyRole insCompany = new PartyRole();
        if("00000079".equals(companyId) || "0001".equals(companyId)) {  // 中国人保
            insCompany.setId("000079");
        }else if("00001419".equals(companyId) || "0004".equals(companyId)) { // 中国人寿
            insCompany.setId("001419");
        }else if("00000080".equals(companyId)) { // 永诚
            insCompany.setId("000080");
        }else if("00000839".equals(companyId)) { // 阳光
            insCompany.setId("000839");
        }else {
            insCompany = null;
        }
        return insCompany;
    }

    /*
    * 保存车辆信息
    * */
    private CarBase saveCarInfo(SimpleRequest simpleRequest) {
        JSONObject simpleRequestObj = simpleRequest.getJO();
        // 获取对应模型
        CarBase carBase = simpleRequest.getO(CarBase.class);
        CarBusiness carBusiness = simpleRequest.getO(CarBusiness.class);
        CarMaintenance carMaintenance = simpleRequest.getO(CarMaintenance.class);

        // 查询车辆信息是否已经存在
        CarBase carBaseOld = carBaseRepository.findFirstByOriginEquals(carBase.getOrigin());
        if (carBaseOld != null) {
            carBusiness.setId(carBaseOld.getCarBusiness().getId());
            carBusiness.setVersion(carBaseOld.getCarBusiness().getVersion());
            carMaintenance.setId(carBaseOld.getCarMaintenance().getId());
            carMaintenance.setVersion(carBaseOld.getCarMaintenance().getVersion());
            carBase.setId(carBaseOld.getId());
            carBase.setVersion(carBaseOld.getVersion());
        }
        carBusiness.setCar(carBase);
        carMaintenance.setCar(carBase);
        // 车漆类型 跟脚本一样为默认普通漆 yyerp没值
        Enumeration paintType = new Enumeration();
        paintType.setId("000210");
        carBase.setPaintType(paintType);
        // 配置车型编码
        String carConfigurationId = simpleRequestObj.getString("PZCXID");
        if(carConfigurationId != null) {
            // yyerp 没有严格按照定义， 所以存在非定义数据
            CarConfiguration carConfiguration = carConfigurationRepository.findOne(carConfigurationId);
            if(carConfiguration != null) {
                carConfiguration.setId(carConfigurationId);
                carBase.setCarConfiguration(carConfiguration);
            }
        }
        // 年审结果
        int NSJYQK = simpleRequestObj.getInteger("NSJYQK") != null ? simpleRequestObj.getInteger("NSJYQK") : 2;
        if(NSJYQK != 2) {
            Enumeration annualReviewResult = new Enumeration();
            if(NSJYQK == 0) { // 合格
                annualReviewResult.setId("000215");
            }else { // 不合格
                annualReviewResult.setId("000214");
            }
            carBusiness.setAnnualReviewResult(annualReviewResult);
        }
        // 环保检查结果
        int HBDBQK = simpleRequestObj.getInteger("HBDBQK") != null ? simpleRequestObj.getInteger("HBDBQK") : 2;
        if(HBDBQK != 2) {
            Enumeration tailGasQualified = new Enumeration();
            if(HBDBQK == 0) { // 合格
                tailGasQualified.setId("000213");
            }else { // 不合格
                tailGasQualified.setId("000212");
            }
            carBusiness.setTailGasQualified(tailGasQualified);
        }
        carBase.setCarBusiness(carBusiness);
        carBase.setCarMaintenance(carMaintenance);
        return carBaseRepository.saveAndFlush(carBase);
    }

}
